package com.netty.demo.heartbeat;

import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

public class HeartbeatServerHandler extends ChannelInboundHandlerAdapter{
	
	// Return a unreleasable view on the given ByteBuf
		// which will just ignore release and retain calls.
		private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled
				.unreleasableBuffer(Unpooled.copiedBuffer("Heartbeat",
						CharsetUtil.UTF_8)); 
		
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			System.out.println("server reciverd:"+msg.toString());
			ctx.writeAndFlush(Unpooled.copiedBuffer("nihao",CharsetUtil.UTF_8));
		}
		
		@Override
		public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
				throws Exception {

			if (evt instanceof IdleStateEvent) {
				IdleStateEvent event = (IdleStateEvent) evt;
				String type = "";
				if (event.state() == IdleState.READER_IDLE) {
					type = "读超时";
				} else if (event.state() == IdleState.WRITER_IDLE) {
					type = "写超时";
				} else if (event.state() == IdleState.ALL_IDLE) {
					type = "读写 超时";
				}

				ctx.writeAndFlush(HEARTBEAT_SEQUENCE.duplicate()).addListener(
						ChannelFutureListener.CLOSE_ON_FAILURE);
	 
				System.out.println( ctx.channel().remoteAddress()+"心跳状态：" + type);
			} else {
				super.userEventTriggered(ctx, evt);
			}
		}
	
}
